package com.qf.service.impl;

import com.qf.mapper.DeviceGatherMapper;
import com.qf.mapper.DeviceMapper;
import com.qf.mapper.DeviceTypeMapper;
import com.qf.mapper.FarmMapper;
import com.qf.model.Device;
import com.qf.model.DeviceGather;
import com.qf.model.DeviceType;
import com.qf.model.Farm;
import com.qf.page.PageResult;
import com.qf.page.QueryPageBean;
import com.qf.service.DeviceGatherService;
import com.qf.service.DeviceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ThreadPoolExecutor;

@Service
public class DeviceGatherServiceImpl implements DeviceGatherService {
    @Autowired
    private DeviceGatherMapper deviceGatherMapper;
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private DeviceTypeMapper deviceTypeMapper;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;



//    @Override
//    @Transactional
//    public int add(Device device) {
//        device.setUpdateTime(new Date());
//        return deviceMapper.add(device);
//    }
//
//    @Override
//    public Device findById(int id) {
//        return deviceMapper.findById(id);
//    }
//
//
//    @Override
//    @Transactional
//    public int edit(Device device) {
//        device.setUpdateTime(new Date());
//        int i = deviceMapper.edit(device);
//        return i;
//    }
//
//
//    @Override
//    @Transactional
//    public int delete(int id) {
//        return deviceMapper.delete(id);
//    }

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        Integer CurrentPage = queryPageBean.getCurrentPage();
        Integer PageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        PageResult pageResult = new PageResult();
        List<DeviceGather> rows = deviceGatherMapper.findPage((CurrentPage - 1) * PageSize, PageSize, queryString);
        for (DeviceGather row : rows) {
            Device device = deviceMapper.findById(row.getDeviceId());
            row.setDeviceName(device.getName());
            row.setDeviceSn(device.getSn());
            DeviceType deviceType = deviceTypeMapper.findById(device.getTypeId());
            row.setDeviceType(deviceType.getName());
        }

        Long total = deviceGatherMapper.count(queryString);
        pageResult.setRows(rows);
        pageResult.setTotal(total);
        return pageResult;
    }


    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;

    /**
     * 定时器增加设备事件
     */
    @Transactional
    @Scheduled(cron = "0/2 * * * * ? ")
    public void autoInsert(){
        System.out.println("定时任务开启"+new Date());
        List<Integer> deviceIds = deviceMapper.getDeviceIds();
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("7b55");
        Random random = new Random();
        Integer integer = deviceIds.get(random.nextInt(deviceIds.size()));
        String body = integer+"a"+random.nextInt(40);
        String message = stringBuilder.append(body).append("7a55").toString();
        if (message.length() >= 12){
            if (message.startsWith("7b55")){
                if (message.endsWith("7a55")){
                    Thread thread = new Thread(new Runnable() {
                        @Override
                        public void run() {
                            int a = message.indexOf("a", 4);
                            //a表示body中a的索引
                            int id = Integer.parseInt(message.substring(4,a));
                            int b = message.indexOf("a",a+1);
                            //b代表7a55中a的索引
                            Float basicData =Float.parseFloat(message.substring(a+1,b-1)) ;
                            DeviceGather deviceGather = new DeviceGather();
                            deviceGather.setDeviceId(id);
                            deviceGather.setBasicData(basicData);
                            deviceGather.setGatherTime(new Date());
                            int i = deviceGatherMapper.add(deviceGather);
                            if (i>0){
                                System.out.println("添加成功,事件采集时间"+new Date());

                                double max = Double.parseDouble(stringRedisTemplate.opsForValue().get("thresholdMax" + Integer.toString((int)deviceGather.getDeviceId()))) ;
                                double min = Double.parseDouble(stringRedisTemplate.opsForValue().get("thresholdMin"+Integer.toString((int)deviceGather.getDeviceId())));
                                if (deviceGather.getBasicData() >= max || deviceGather.getBasicData()<= min){
                                    System.out.println("设备报警，当前数据"+deviceGather.getBasicData()+",最大阈值："+max+",最小阈值："+min);
                                }else {
                                    System.out.println("无事发生当前数据"+deviceGather.getBasicData());
                                }
                            }
                        }
                    });
                    threadPoolExecutor.execute(thread);

                }
            }
        }



    }


}
